package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.Log;
import web.JSONMessage;

import model.Enterprise;
import model.Person;
import model.UserAccount;
import model.type.SubjectType;
import db.ImbiConnection;
import facade.CustomerFacade;

public class CustomerController extends HttpServlet{

	private static final long serialVersionUID = 1L;
		
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount)request.getSession().getAttribute("user");
		if(u != null){
			try{
				int type = Integer.parseInt(request.getParameter("type"));
				int id = Integer.parseInt(request.getParameter("id"));
				if(type == SubjectType.ENTERPRISE){					
					Enterprise e = ImbiConnection.getEnterpriseDAO().find(id);
					if(!e.isCustomer()){	
						CustomerFacade.makeCustomer(e);
						response.getWriter().write(JSONMessage.message("Enterprise made to customer."));
					}
					else response.getWriter().write(JSONMessage.errorMessage("Enterprise is already a customer"));					
				} else if (type == SubjectType.PERSON){
					Person p = ImbiConnection.getPersonDAO().find(id);
					if(!p.isCustomer()){ 
						CustomerFacade.makeCustomer(p);
						response.getWriter().write(JSONMessage.message("Person made to customer."));
						Log.write(u.getUsername()+" added Customer: subject: "+id+" type: "+type);
					}
					else response.getWriter().write(JSONMessage.errorMessage("Person is already a customer"));					
				}				
			} catch(Exception e){
				response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
			}
			
			
		}
	}
}
